<?php

namespace App\Http\Controllers\V1;

use App\Http\Controllers\ApiBaseController;
use App\Http\Requests\SysUserRequest;
use App\Models\SysRole;
use App\Models\SysUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Testing\Fluent\Concerns\Has;

class SysUserController extends ApiBaseController
{
    public function index(Request $request){
        $paginator = SysUser::filter($request->all())->where('user_type',$this->customer_config_map['sys_type'])->with('dept')->paginate($this->pageSize);
        return success(page_format($paginator));
    }

    public function show(Request $request, SysUser $model){
        $id = $request->get('id',0);
        $data = $model->where('user_type',$this->customer_config_map['sys_type'])->find($id);
        $roles = SysRole::all();
        $user_roleids = DB::table('sys_user_role')->where('user_id', $id)->pluck('role_id');
        return success([
            'data' => $data,
            'roles' => $roles,
            'roleIds' => $user_roleids
        ]);
    }

    public function create(SysUserRequest $request){
//        $params = $request->all();
        $params = $request->except(['balance','credit','api_secret','user_type']);

        DB::transaction(function () use ($params) {
            $params['user_type'] = $this->customer_config_map['sys_type'];
            $user = SysUser::create($params);
            $user_id = $user->id;
            $roleIds = $params['roleIds'];
            if(count($roleIds) > 0){
                foreach ($roleIds as $role_id){
                    $add_datas[] = [
                        'user_id' => $user_id,
                        'role_id' => $role_id,
                    ];
                }
                DB::table('sys_user_role')->where('user_id', $user_id)->delete();
                DB::table('sys_user_role')->insertOrIgnore($add_datas);
            }else{
                DB::table('sys_user_role')->where('user_id', $user_id)->delete();
            }
        });
        return success([],'更新成功');
    }

    public function update(SysUserRequest $request, SysUser $model)
    {
        $params = $request->except(['password','login_ip','login_time','create_by','balance','credit','api_secret','user_type']);
        $id = $request->post('id');
        $user = $model->where('user_type',$this->customer_config_map['sys_type'])->find($id);
        if(!$user){
            return error('数据不存在');
        }
        DB::transaction(function () use ($params, $user) {
            $user->update($params);
            $user_id = $user->id;
            $roleIds = $params['roleIds'];
            if(count($roleIds) > 0){
                foreach ($roleIds as $role_id){
                    $add_datas[] = [
                        'user_id' => $user_id,
                        'role_id' => $role_id,
                    ];
                }
                DB::table('sys_user_role')->where('user_id',$user_id)->delete();
                DB::table('sys_user_role')->insertOrIgnore($add_datas);
            }else{
                DB::table('sys_user_role')->where('user_id',$user_id)->delete();
            }
        });
        return success([],'更新成功');
    }

    public function destroy($ids, Request $request, SysUser $model){
        $id_arr = explode(',', $ids);
        $model->destroy($id_arr);
        return success([],'删除成功');

    }

    public function changeStatus(Request $request, SysUser $model){
        $params = $request->all();
        $id = $request->post('user_id');
        $status = $request->post('status');

        $role = $model->find($id);
        if(!$model){
            return error('数据不存在');
        }
        $role->update([
            'status' => $status
        ]);
        return success([],'更新成功');
    }
    public function resetPwd(Request $request, SysUser $model){
        $params = $request->all();
        $id = $request->post('user_id');
        $password = $request->post('password');

        $user = $model->find($id);
        if(!$model){
            return error('数据不存在');
        }
        /*
        $user->update([
            'password' => Hash::make($password),
        ]);
        */
        $user->password = trim($password);
        $user->save();

        return success([],'更新成功');
    }

    public function changePwd(Request $request){
        $user = auth()->user();
        if(Hash::check($request->post('old_password'),$user->password) == false){
            return error('旧密码不匹配');
        }
//        $user->password = Hash::make(trim($request->post('new_password')));
        $user->password = trim($request->post('new_password'));
        $user->save();
        return success([],'修改成功');

    }

    public function profile(SysUser $model){
        $user = $model->with(['dept','roles'])->where('id',auth()->id())->first();
        if(!$user){
            return error('数据不存在');
        }
        $roles = $user->roles()->pluck('role_name');
        return success([
            'data' => $user,
            'roleGroup' => implode("/",$roles ? $roles->toArray() : [])
        ]);
    }

}
